package com.kgc.scd.async;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created On : 2022/11/16.
 * <p>
 * Author : Administrator
 * <p>
 * Description: 异步定时
 */
@Slf4j
@Component
public class AsyncSchedule {


    @Async
    public void setAsyncSchedule(String userId, Date date) {
        //时间串
        long bushGoodsStartTime = date.getTime();

        Date nowTime = new Date();
        //比较当前时间和抢购时间的是否小于一个小时,小于一个小时立即发送消息
        long nowTimeLong = nowTime.getTime();
        long subMs = bushGoodsStartTime - nowTimeLong;
        //算出还差多少分钟开始抢购
        long subMin = subMs / (60 * 1000);


        TimerTask task = new TimerTask() {
            @Override
            public void run() {
                // 逻辑处理
                log.info("[通知] 用户编号为:" + userId + "的用户你好,你的商品距离抢购还有1小时,请准时去抢购页面进行抢购");
            }
        };

        TimerTask task1 = new TimerTask() {
            @Override
            public void run() {
                // 逻辑处理
                log.info("[通知] 用户编号为:" + userId + "的用户你好,你的商品距离抢购还有"+subMin+"分钟,请及时去抢购页面进行抢购");
            }
        };
        TimerTask task2 = new TimerTask() {
            @Override
            public void run() {
                // 逻辑处理
                log.info("[通知] 用户编号为:" + userId + "的用户你好,你的商品距离抢购已经过期");
            }
        };


        Timer timer = new Timer();
        if (subMs >= 3600 * 1000) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(date);
            calendar.add(Calendar.HOUR_OF_DAY, -1);

            timer.schedule(task, calendar.getTime());
        } else if (subMs < 3600 * 1000 && subMs > 0) {

            timer.schedule(task1, 0);
        } else {
            timer.schedule(task2, 0);
        }


    }


}
